package com.example.demo.config;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Component
@Slf4j
public class CustInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, String> keyList = new HashMap<>();
        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()){
            String key = enumeration.nextElement();
            keyList.put(key, request.getParameter(key));
        }
        //接下来拿取所有的body数据
        String body = ReadAsChars2(request);
        log.info("requestInfo keyList : {} body : {}", JSONObject.toJSONString(keyList), body);
        return super.preHandle(request, response, handler);
    }

    // 方法二
    public static String ReadAsChars2(HttpServletRequest request)
    {
        StringBuilder sb = new StringBuilder();
        InputStream is = null;
        try
        {
            is = request.getInputStream();

            byte[] b = new byte[4096];
            for (int n; (n = is.read(b)) != -1;)
            {
                sb.append(new String(b, 0, n));
            }

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (null != is)
            {
                try
                {
                    is.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();

    }

}
